//
//  BabyTreeRequest.swift
//  eat_known
//
//  Created by 心情 on 2018/8/3.
//  Copyright © 2018年 心情. All rights reserved.
//

import Foundation
import Alamofire
import SwiftSoup

//MARK:- 宝宝树
class BabyTreeRequest: FoodRequestProtocol {
    static func start(keyword: String!, completion: @escaping (Array<Food>?, Error?) -> Void) {
        let urlStr = "http://webview.babytree.com/api/mobile_toolcms/can_eat_search?q=" + keyword.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
        Alamofire.request(urlStr).responseString { (response) in
            do {
                let doc = try SwiftSoup.parse(response.value!, "http://webview.babytree.com")
                var foods: [Food]?
                let list: Elements = try doc.select("div.food-one").select("dl").select("a")
                if list.array().count > 0 {
                    foods = self.parse(list)
                } else if try doc.select("div.detail").first() != nil {
                    if let food = self.parse(doc) {
                        food.detailURL = try urlStr.asURL()
                        foods = [food]
                    }
                }
                completion(foods, nil)
            } catch {
                
            }
        }
    }
}

extension BabyTreeRequest {
    static func parse(_ list: Elements) -> [Food]? {
        do {
            let foods = try list.array().map({ (ele) -> Food in
                let food = Food(FoodSource.BabyTree)
                food.detailURL = try ele.attr("href").asURL()
                food.name = try ele.select("span.title").text()
                food.desc = try ele.select("span.summary").text()
                var style = try ele.select("dt").first()?.attr("style")
                //background-image: url(xxx)
                style?.removeLast()//)
                style?.removeFirst(22)//background-image: url(
                food.imageURL = try style?.asURL()
                let spans = try ele.select("div.status").select("span")
                let phases = try spans.array().map({ (span) -> Phase in
                    let phaseName = try span.child(0).text()
                    let stateName = try String(span.child(1).className().last!)
                    let phaseState = PhaseState.name(phaseName)
                    let foodState = PhaseFoodState.babyTree(stateName)
                    let phase = Phase(state: phaseState, foodState: foodState)
                    return phase
                })
                food.phaseList = phases
                return food
            })
            return foods
        } catch {
            return nil
        }
    }
    
    static func parse(_ doc: Document) -> Food? {
        do {
            let food = Food(FoodSource.BabyTree)
            let ele = try doc.select("div.detail").first()!
            food.name = try doc.select("input#title-detail").val()
            food.desc = try doc.select("div.sub-title").text()
            food.imageURL = try ele.select("img").first()?.attr("src").asURL()
            let spans = try ele.select("h1.caneat-title")
            let phases = try spans.array().map({ (span) -> Phase? in
                let em = try span.select("em").first()
                if em == nil {
                    return nil
                }
                var phaseState = PhaseState.Unknown
                var foodState = PhaseFoodState.Unknown
                if let phaseName = try span.select("em").first()?.text() {
                    phaseState = PhaseState.name(phaseName)
                }
                if let stateName = try span.select("em").last()?.text() {
                    foodState = PhaseFoodState.name(stateName)
                }
                let phase = Phase(state: phaseState, foodState: foodState)
                return phase
            })
            food.phaseList = phases.compactMap{ $0 }
            return food
        } catch {
            return nil
        }
    }
}
